<template>
  <edit-dialog :centerDialogVisible="visible" :tilte="info && info.typeId ? '编辑' : '新增'" @Cancel="handleCancel"
    @Submit="handleSubmit(goodsTypeFormRef)" :width="dialogWidth">
    <template #content>
      <div>
        <el-form ref="goodsTypeFormRef" :rules="rules" :model="form" label-width="80px">
          <el-form-item label="分类" prop="classifyCode">
            <el-select v-model="form.classifyCode" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in goodsClassifyList" :label="item.label" :value="item.value" :key="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="物品类型" prop="goodsType">
            <el-input v-model="form.goodsType" />
          </el-form-item>
          <el-form-item label="保存时限" prop="timeLimit">
            <el-input v-model="form.timeLimit" placeholder="" class="input-with-select">
              <template #append>
                <el-select v-model="form.timeLimitUnit" placeholder="请选择" style="width: 115px">
                  <el-option label="小时" value="H" />
                  <el-option label="天" value="D" />
                  <el-option label="年" value="Y" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" :rows="5" type="textarea" />
          </el-form-item>
        </el-form>
      </div>
    </template>
  </edit-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, defineProps, watch, nextTick, toRaw, computed } from 'vue'
import { useStore } from 'vuex'
import type { FormInstance, FormRules } from 'element-plus'
import { goodsTypeAppend, goodsTypeUpdate } from '@/api/lose/goodsType'
import editDialog from '@/components/editDialog/index.vue'
import { ElMessage } from 'element-plus'

interface RuleForm {
  goodsType: string;
  classifyCode: string;
  timeLimit: number;
  timeLimitUnit: string;
  remarks: string;
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  info: {
    type: Object,
    default: () => null,
  },
})

const emit = defineEmits(['cancel', 'ok'])

const store = useStore()
// 弹窗标题
const dialogWidth = ref('460px')
const goodsTypeFormRef = ref<FormInstance>()
const userInfo = computed(() => store.state.user.userInfo)
const goodsClassifyList = computed(() => store.state.goodsType.loseGoodsClassify)
const form = reactive<RuleForm>({
  goodsType: '',
  classifyCode: '',
  timeLimit: 0,
  timeLimitUnit: 'H',
  remarks: '',
})

const checkTimeLimit = (rule: any, value: any, callback: any) => {
  if (!value) return callback(new Error('请输入保存时限！'))
  if (!/^([1-9][0-9]*)+(.[0-9]{1,2})?$/.test(value)) return callback(new Error('保存实现应为数字（最多两位小数）'))
  callback()
}

const rules = reactive<FormRules<RuleForm>>({
  classifyCode: [{ required: true, message: '请选择分类', trigger: 'blur' }],
  goodsType: [{ required: true, message: '请输入物品类型名称', trigger: 'blur' }],
  timeLimit: [{ required: true, validator: checkTimeLimit, message: '请输入保存时限', trigger: 'blur' }],
  remarks: [{ required: true, message: '请输入备注', trigger: 'blur' }],
})
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let fetch = goodsTypeAppend;
      const payload = { ...form };

      if (props.info?.typeId) {
        fetch = goodsTypeUpdate;
        payload.typeId = props.info.typeId;
        payload.mender = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          userName: userInfo.value.userName,
          organId: userInfo.value.organId || '',
          organName: userInfo.value.organName || ''
        }
      } else {
        payload.creator = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          userName: userInfo.value.userName,
          organId: userInfo.value.organId || '',
          organName: userInfo.value.organName || ''
        }
      }

      console.log(payload);
      payload.timeLimit = Number(payload.timeLimit)
      let res = null;
      try {
        res = await fetch(payload);
      } catch {
      }
      if (res?.code === '1') {
        emit('ok')
        ElMessage.success(props.info?.typeId ? '修改成功！' : '新增成功！');
      } else {
        ElMessage.error(res?.message || '新增失败，请重试！');
      }
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

const handleCancel = () => {
  emit('cancel')
}

watch(() => props.visible, (val, oldVal) => {
  console.log(val, oldVal)
  if (val && val !== oldVal) {
    console.log('=================', props.info)
    nextTick(() => {
      if (props.info) {
        const info = toRaw(props.info);
        console.log(props.info, info?.goodsType);
        form.goodsType = info?.goodsType || '';
        form.classifyCode = info?.classifyCode || '';
        form.timeLimit = info?.timeLimit || '';
        form.timeLimitUnit = info?.timeLimitUnit || 'H';
        form.remarks = info?.remarks || '';
      } else {
        form.goodsType = '';
        form.classifyCode = '';
        form.timeLimit = '';
        form.timeLimitUnit = 'H';
        form.remarks = '';
      }
    })
  }
})
</script>